<template>
<div :z-index="zIndex">
    <div v-if="mode=='image'" class="images-box">
        <!-- 一张图片 -->
        <template v-if="isStr">
            <div v-if="value" class="imgs" :style="`width:${width};height:${height};`">
                <img :src="value" alt="">
                <div class="rowp">
                    <span @click="removeImg()" v-if="!readonly" title="删除图片" class="el-icon-delete"></span>
                    <span @click="viewPicture()" title="查看图片" class="el-icon-zoom-in"></span>
                </div>
            </div>
        </template>
        <!-- 多张图片 -->
        <template v-else-if="Object.prototype.toString.call(value) == '[object Array]'">
            <div
            v-for="(item,i) in value"
            :key="i" class="imgs"
            :style="`width:${width};height:${height};`">
                <img :src="item" alt="">
                <div class="rowp">
                    <span @click="removeImg(i)" v-if="!readonly" title="删除图片" class="el-icon-delete"></span>
                    <span @click="viewPicture(i,2)" title="查看图片" class="el-icon-zoom-in"></span>
                </div>
            </div>
        </template>

        <div v-show="loading" class="loading" :style="[{width:width},{height:height}]">
            <i class="el-icon-loading"></i>
        </div>
        <div v-show="iconLoading" :style="[{width:width},{height:height}]" class="add-img">
            <span class="el-icon-plus"> </span>
            <input type="file" :disabled="loading" @change="uploadImg" title="选择要上传的图片" :multiple="!isStr" ref="imgTop" accept="image/jpeg,image/jpg,image/png">
        </div>
    </div>

    <div v-else-if="mode=='video'" class="video-box">
        <div v-show="value" class="video">
            <video :src="value" :style="videoStye" controls preload></video>
            <i @click="videoDel" v-if="!readonly" title="删除视频" class="el-icon-error"></i>
        </div>
        <div v-show="loading" class="loading" :style="[{width:width},{height:height}]">
            <i class="el-icon-loading"></i>
            <!-- 上传进度不好用,暂时放弃 -->
            <!-- <meter  :value="progress" min="0" max="100"></meter> -->
        </div>
        <div v-show="iconLoading" :style="[{width:width},{height:height}]" class="add-img">
            <span class="el-icon-plus"> </span>
            <input type="file" :disabled="loading" @change="uploadVideo" title="选择要上传的视频" multiple ref="videoTop" accept="video/*">
        </div>
    </div>
    <!-- <el-dialog custom-class="images" top="0%" :visible.sync="isImg" append-to-body>
        <img class="images-box" @click="isImg = false" :src="imgSrc"/>
    </el-dialog> -->
    <el-image-viewer
        v-if="isImg"
        :z-index="6000"
        :on-close="closeViewer"
        :initial-index="imgIndex"
        :url-list="imgSrc"
    />
</div>
</template>
<script>
    {/*更新日志
        v1.0.6  --修改视频上传bug
        v1.1.0  --修改图片排版样式 新增图片只读 新增自定义大小限制 移出video,imgList统一换成v-model作为地址
    */}
    /**
	 * modal 图片上传 v1.1.0  --修改排版样式 新增图片只读
	 * @description 图片上传
     * @property {String} back 背景色
     * @property {Boolean} readonly 只读
	 * @property {String | Number} z-index 层级(默认10)
     * @property {String} width 图片(包括添加)的宽度(请带上单位px)
     * @property {Number} maxNum 最大上传数(默认9)
     * @property {Number | String} size 图片或视频大小限制 (单位:MB)
     * @property {Array | String} imgList 图片地址如果是字符串类型那就只能上传一张
     * @property {String} mode 模式(默认image): image图片 video视频
     * @property {Object} videoStye 视频样式
	 * @event {Function} verify 图片验证回调
	 * @event {Function} cancel 取消按钮被点击
	 * @example <vs-uploading :v-model="value" ></vs-uploading>
	 */
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
import { addClass, removeClass } from 'element-ui/src/utils/dom';
export default {
    components: {
        ElImageViewer,
    },
    data(){
        return{
            progress:0,
            loading:false,
            isImg:false,
            imgSrc:[],
            imgIndex:0,
            isStr:false,//判断是单个视频还是多视频
        }
    },
    props:{
        value:{
            type:[Array,String],
            default(){
                return []
            }
        },
        readonly:{
            type:Boolean,
            default:false,
        },
        back:{
            type:String,
            default:'#ffffff'
        },
        vname:{
            type:String,
            default:'',
        },
        videoStye:{
            type:Object,
            default(){
                return{}
            }
        },
        mode:{
            type:String,
            default:'image'
        },
        size:{
            type:[String,Number],
            default:10,
        },
        // 层级z-index
        zIndex: {
            type: [Number, String],
            default: 10
        },
        width:{
            type:String,
            default:'150px'
        },
        height: {
            type: String,
            default: "150px",
        },
        maxNum:{
            type:Number,
            default:9
        },
        //是否压缩图片大小
        isCompress:{
            type:Boolean,
            default:false,
        },
    },
    watch:{
        value(val){
            this.isStr = Object.prototype.toString.call(val) == '[object String]';
            // console.log(this.isStr,"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@",val,this.value);
            let isVer = false;
            isVer = (this.isStr?val:val.length)?true:false;
            this.$emit('verify',isVer);
            this.$parent.$emit("el.form.blur");
            this.$parent.$emit("el.form.change");
        }
    },
    computed:{
        iconLoading(){
            if(this.readonly)return false;
            if(this.isStr){
                return !this.value && !this.loading
            }else{
                return this.value.length < this.maxNum && !this.loading
            }
        }
    },
    created(){

    },
    mounted(){
        this.isStr = Object.prototype.toString.call(this.value) == '[object String]';
        // console.log(this.isStr,"@@#$!@#$!@",Object.prototype.toString.call(this.value),this.value);
    },
    methods:{
        viewPicture(i,type=1){//type:1单图查看   2多图查看
            this.isImg=true;
            addClass(document.body,'el-popup-parent--hidden')
            if(type==1){
                this.imgSrc = [this.value];
                this.imgIndex = 0;
            }else{
                this.imgSrc = this.value;
                this.imgIndex = i;
            }
        },
        closeViewer(){ //关闭
            this.isImg = false;
            removeClass(document.body, 'el-popup-parent--hidden');
        },
        videoDel(){//删除视频
            // this.$emit('update:value','');
            this.$emit('input', '');
        },
        async uploadVideo(){//上传视频
            let files = this.$refs.videoTop.files[0];
            if(!files)return;
            if(files.size > this.size*1024*1024){
                return this.$message.error(`视频大小不能超过${this.size}MB`);
            }
            let formData = new FormData();
            formData.append("files", files);
            this.loading = true;
            this.$Http.upload(formData).then(({code,data}) => {
                // 完成
                this.loading = false;
                if(code){
                    this.$message.success("视频上传成功！")
                    // this.$emit('update:video',data)
                    this.$emit('input', data);
                    this.$refs.videoTop.value ="";
                }
            }).catch((error) => {
                this.$refs.videoTop.value ="";
                this.loading = false;
                // 出错
            })
            // return;
        },
        removeImg(i){//删除图片
            this.isStr ? this.$emit('input', '') : this.value.splice(i,1);
        },
        uploadImg(){//图片上传  8  4
            let type = ['image/jpeg','image/jpg','image/png']
            let files = [...this.$refs.imgTop.files];
            // 剩余能上传图片的数量
            let maxNum = this.isStr ? 1 : this.maxNum - this.value.length ;
            if(!files.length||!maxNum){
                return
            }else if(files.length>maxNum){
                files.splice(maxNum,files.length);
            }
            let ajaxNum = 0;
            files.forEach(async (v,i)=>{
                if(v.size > this.size*1024*1024){
                    return this.$message.error(`图大小不能超过${this.size}MB`);
                }
                if(type.findIndex((v2)=>v2==v.type)!=-1){
                    let compressedPicture = v;
                    this.loading = true;
                    if(this.isCompress){
                        compressedPicture = await this.utils.compress(v,700,700,0.8)
                    }
                    let formData = new FormData();
                    console.log(compressedPicture,'压缩后'+this.isCompress+'的文件',v);
                    formData.append("files", compressedPicture);
                    let {code,data} = await this.$Http.upload(formData);
                    ajaxNum++;
                    if(code){
                        this.$message.success("图片上传成功！");
                        console.log( this.isStr,'da this.isStrta');
                        this.isStr?this.$emit('input',data):this.value.push(data);
                        this.$refs.imgTop.value = "";
                    }
                    if(ajaxNum==files.length){
                        // this.$loading.hide()
                        this.loading = false;
                    }
                }else this.$message.error('上传格式不正确');

            })
        },
    }
}
</script>
<style lang="scss" scoped>
::v-deep .el-dialog{
    min-width: 50%;
    width: auto;
}
.images{
    .images-box{
        margin: 0 auto;
        max-width: 95vw;
        max-height: 80vh;
        width: auto;
        background: url(https://api.yiweika.net/uploads/2021/07/31/imagesVFQC5GaX4gob2lCV.png) ;
    }
}
.video-box{
    .video{
        width: max-content;
        position: relative;
        video{
            max-width: 480px;
            max-height: 480px;
            object-fit: scale-down;
        }
        .el-icon-error{
            position: absolute;
            top: 0px;
            right: 0px;
            color: #545454;
            font-size: 30px;
            background-color: #fff;
            border-radius: 50%;
            cursor: pointer;
            transform: translate(50%,-50%);
        }
    }
}
.images-box{
    display: flex;
    flex-wrap: wrap;
    grid-row-gap: 20px;
    grid-column-gap: 20px;
    // width: 800px;
    // padding-bottom: 30px;
    // border-bottom: #F2F2F2 1px solid;
    .imgs{
        background: url(https://api.yiweika.net/uploads/2021/07/31/imagesVFQC5GaX4gob2lCV.png) ;
        position: relative;
        width: 120px;
        height: 120px;
        border-radius: 5px;
        // margin-top: 22px;
        // margin-right: 32px;
        // &:nth-child(4n){
        //     margin-right: 0;
        // }
        &:hover .rowp{
            opacity: 1;
            // transition: all 1s linear;
        }
        .rowp{
            position: absolute;
            top: 0;
            width: 100%;
            height: 100%;
            background: #0005;
            display: flex;
            justify-content: space-evenly;
            align-items: center;
            color: #fff;
            opacity: 0;
            transition: opacity .3s;
            border-radius: 5px;
            span{
                padding: 10px;
                font-size: 24px;
                cursor: pointer;
            }
        }
        img{
            border-radius: 5px;
            display: block;
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

    }
}
.loading{
    // margin-top: 22px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    meter{
        margin-top: 20px;
        width: 100%;
    }
    .el-icon-loading{
        color: #bbb8b8;
        font-size: 34px;
        height: min-content;
    }
}
.add-img{
    position: relative;
    // margin-top: 22px;
    display: flex;
    cursor: pointer;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 150px;
    height: auto;
    color: #bbb8b8;
    border: 1px solid #D9D9D9;
    border-radius: 5px;
    transition: .3s;
    &:hover{
        border-color: #409eff;
        color: #409eff;
    }
    input{
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        opacity: 0;
        cursor: pointer;
        font-size:0;
    }
    .el-icon-plus{
        // margin-bottom: 10px;
        font-size: 30px;
    }
}
::v-deep.el-dialog__wrapper{
    // background: red;
    display: flex;
    justify-content: center;
    align-items: center;
    // height: 100vh;
    // .el-dialog{
    //     transform: translateY(-50%);
    // }
}
::v-deep.el-image{
    display: block;
    margin: 0 auto;

}
</style>